using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Admin.NET.Application;
using Admin.NET.Application.Entity.Business;
using Admin.NET.Application.Service.Sms;
using Admin.NET.Core;
using Admin.NET.Core.Service;
using Furion.DataEncryption;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Furion.JsonSerialization;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NewLife.Caching;
using SqlSugar;
using TencentCloud.Sms.V20210111.Models;
using Yitter.IdGenerator;

namespace Admin.Net.Plugin.Api;

[ApiDescriptionSettings(new string[] { "业务应用" }, Order = 100)]
public class TenantAppService : IDynamicApiController, ITransient, IPrivateDependency
{
	public class DeviceAlarmOut
	{
		public int Error { get; set; }

		/// <summary>
		/// 欠费
		/// </summary>
		public int Arrears { get; set; }

		/// <summary>
		/// 电量不足(余额不足)
		/// </summary>
		public int Insufficient { get; set; }

		/// <summary>
		/// 断电
		/// </summary>
		public int OffLine { get; set; }
	}

	public class AppIsSucessCustomer
	{
		public bool IsCustomer { get; set; }

		public bool HasDevice { get; set; }
	}

	public class AppAddTenantInput : AddTenantInput
	{
		/// <summary>
		/// 验证码
		/// </summary>
		public string PhoneNum { get; set; }

		/// <summary>
		/// 密码
		/// </summary>
		public string Password { get; set; }
	}

	/// <summary>
	/// 电表数据
	/// </summary>
	public class AppAddElement
	{
		/// <summary>
		/// 电表id
		/// </summary>
		public string MeterNo { get; set; }
	}

	public class TenantDevviceOut
	{
		public int AllCount { get; set; }

		/// <summary>
		/// 在线(现在修改调整为在线合闸)
		/// </summary>
		public int Line { get; set; }

		/// <summary>
		/// 离线
		/// </summary>
		public int OffLine { get; set; }

		/// <summary>
		/// 拉闸（现在修改为在线拉闸）
		/// </summary>
		public int State { get; set; }

		public int BUZUYIDUN { get; set; }
	}

	public class TenantIncomeOut
	{
		/// <summary>
		/// 钱
		/// </summary>
		public string Money { get; set; }

		/// <summary>
		/// 耗电量
		/// </summary>
		public string PowerConsumption { get; set; }

		/// <summary>
		/// 耗水量
		/// </summary>
		public string WaterConsumption { get; set; }
	}

	public class TenantWaterUsage
	{
		public string AllUse { get; set; }

		public string MonthUse { get; set; }
	}

	private readonly SqlSugarRepository<PowerConsumptionRecord> _reppower;

	private readonly IHttpContextAccessor _httpContextAccessor;

	private readonly SqlSugarRepository<PaymentRecord> _reppay;

	private readonly SqlSugarRepository<MessageConfig> _rep;

	private readonly ICache _cache;

	private readonly SqlSugarRepository<SysTenant> _sysTenantRep;

	private readonly SqlSugarRepository<SysOrg> _sysOrgRep;

	private readonly SqlSugarRepository<SysRole> _sysRoleRep;

	private readonly SqlSugarRepository<SysPos> _sysPosRep;

	private readonly SqlSugarRepository<SysUser> _sysUserRep;

	private readonly SqlSugarRepository<SysUserExtOrg> _sysUserExtOrgRep;

	private readonly SqlSugarRepository<SysRoleMenu> _sysRoleMenuRep;

	private readonly SqlSugarRepository<SysUserRole> _userRoleRep;

	private readonly SysUserRoleService _sysUserRoleService;

	private readonly SysRoleMenuService _sysRoleMenuService;

	private readonly SysConfigService _sysConfigService;

	private readonly SysCacheService _sysCacheService;

	private readonly SqlSugarRepository<ElectricMeter> _repEle;

	private readonly SqlSugarRepository<Room> _reRoom;

	private readonly SqlSugarRepository<EarlyWarning> _repwring;

	private readonly SqlSugarRepository<UserMerchantKT> _userKt;

	private readonly UserManager _userManager;

	public TenantAppService(IHttpContextAccessor httpContextAccessor, SqlSugarRepository<EarlyWarning> repwring, SqlSugarRepository<Room> reRoom, SqlSugarRepository<ElectricMeter> repEle, SqlSugarRepository<PaymentRecord> reppay, SqlSugarRepository<PowerConsumptionRecord> reppower, SqlSugarRepository<MessageConfig> rep, ICache cache, SqlSugarRepository<SysTenant> sysTenantRep, SqlSugarRepository<SysOrg> sysOrgRep, SqlSugarRepository<SysRole> sysRoleRep, SqlSugarRepository<SysPos> sysPosRep, SqlSugarRepository<SysUser> sysUserRep, SqlSugarRepository<SysUserExtOrg> sysUserExtOrgRep, SqlSugarRepository<SysRoleMenu> sysRoleMenuRep, SqlSugarRepository<SysUserRole> userRoleRep, SysUserRoleService sysUserRoleService, SysRoleMenuService sysRoleMenuService, SysConfigService sysConfigService, SysCacheService sysCacheService, UserManager userManager, SqlSugarRepository<UserMerchantKT> userKt)
	{
		_userKt = userKt;
		_httpContextAccessor = httpContextAccessor;
		_reRoom = reRoom;
		_reRoom = reRoom;
		_repEle = repEle;
		_reppay = reppay;
		_reppower = reppower;
		_sysTenantRep = sysTenantRep;
		_sysOrgRep = sysOrgRep;
		_sysRoleRep = sysRoleRep;
		_sysPosRep = sysPosRep;
		_sysUserRep = sysUserRep;
		_sysUserExtOrgRep = sysUserExtOrgRep;
		_sysRoleMenuRep = sysRoleMenuRep;
		_userRoleRep = userRoleRep;
		_sysUserRoleService = sysUserRoleService;
		_sysRoleMenuService = sysRoleMenuService;
		_sysConfigService = sysConfigService;
		_sysCacheService = sysCacheService;
		_rep = rep;
		_cache = cache;
		_repwring = repwring;
		_userManager = userManager;
	}

	/// <summary>
	/// 查询设备是否完成 操作
	/// </summary>
	/// <returns></returns>
	[HttpGet("/app/getissucess")]
	public async Task<AppIsSucessCustomer> GetAPPIsSucess()
	{
		AppIsSucessCustomer isSucessCustomer = new AppIsSucessCustomer();
		AppIsSucessCustomer appIsSucessCustomer = isSucessCustomer;
		appIsSucessCustomer.IsCustomer = await (from u in _userKt.AsQueryable()
			where u.UserId == (long?)_userManager.UserId
			select u).AnyAsync();
		AppIsSucessCustomer appIsSucessCustomer2 = isSucessCustomer;
		appIsSucessCustomer2.HasDevice = await _repEle.AsQueryable().AnyAsync();
		return isSucessCustomer;
	}

	/// <summary>
	/// 设备预警信息
	/// </summary>
	/// <returns></returns>
	[HttpGet("/app/tenantalarm")]
	public async Task<DeviceAlarmOut> DeviceAlarm()
	{
		DeviceAlarmOut deviceAlarmOut = new DeviceAlarmOut();
		var list = await (from u in _reRoom.AsQueryable()
			where u.Balance <= 50m
			select new { u.Balance, u.Id }).ToListAsync();
		List<long> roomIds = list.Select(u => u.Id).ToList();
		var meterInfo = await (from u in _repEle.AsQueryable()
			where u.RoomId != null && roomIds.Contains(u.RoomId.Value)
			group u by u.RoomId into u
			select new
			{
				RoomId = u.RoomId,
				count = SqlFunc.AggregateCount(u.RoomId)
			}).ToListAsync();
		deviceAlarmOut.Arrears = meterInfo.Where(s => (from u in list
			where u.Balance < 0m
			select u.Id).ToList().Contains(s.RoomId.Value)).Sum(s => s.count);
		deviceAlarmOut.Insufficient = meterInfo.Sum(u => u.count) - deviceAlarmOut.Arrears;
		int offline = await (from u in _repEle.AsQueryable()
			where u.GateStatus == 0 && u.SignalStatus == 1
			select u).CountAsync();
		deviceAlarmOut.Error = await (from x in _repwring.Context.Queryable<EarlyWarning>()
			where x.Status != 2
			select x).CountAsync();
		deviceAlarmOut.OffLine = offline;
		return deviceAlarmOut;
	}

	/// <summary>
	/// 获取信息设备在线离线
	/// </summary>
	/// <returns></returns>
	[HttpGet("/app/tenantdevvice")]
	public async Task<TenantDevviceOut> GetDevice()
	{
		TenantDevviceOut tenantDevviceOut = new TenantDevviceOut();
		var result = await (from u in _repEle.AsQueryable()
			group u by new { u.GateStatus, u.SignalStatus } into u
			select new
			{
				GateStatus = u.GateStatus,
				SignalStatus = u.SignalStatus,
				count = SqlFunc.AggregateCount(u.GateStatus)
			}).ToListAsync();
		tenantDevviceOut.AllCount = result.Sum(u => u.count);
		tenantDevviceOut.Line = result.Where(u => u.SignalStatus == 1 && u.GateStatus == 1).Sum(u => u.count);
		tenantDevviceOut.OffLine = result.Where(u => u.SignalStatus == 0).Sum(u => u.count);
		tenantDevviceOut.State = result.Where(u => u.GateStatus == 0 && u.SignalStatus == 1).Sum(u => u.count);
		return tenantDevviceOut;
	}

	/// <summary>
	/// 获取信息设备在线离线
	/// </summary>
	/// <returns></returns>
	[HttpGet("/app/tenantwaterdevvice")]
	public async Task<TenantDevviceOut> GetWaterDevice()
	{
		TenantDevviceOut tenantDevviceOut = new TenantDevviceOut();
		var result = await (from u in _repEle.Context.Queryable<WaterDevice>()
			group u by new { u.IsOnline } into u
			select new
			{
				IsOnline = u.IsOnline,
				count = SqlFunc.AggregateCount(u.IsOnline)
			}).ToListAsync();
		tenantDevviceOut.AllCount = result.Sum(u => u.count);
		tenantDevviceOut.Line = result.Where(u => u.IsOnline == 1).Sum(u => u.count);
		tenantDevviceOut.OffLine = result.Where(u => u.IsOnline == 0).Sum(u => u.count);
		var deviceInfo = _repEle.Context.Queryable<WaterDevice>().LeftJoin((WaterDevice o, WaterPriceRule cus) => o.PriceRuleId == (long?)cus.Id).LeftJoin((WaterDevice o, WaterPriceRule cus, Room roo) => o.RoomId == (long?)roo.Id)
			.Select((WaterDevice o, WaterPriceRule cus, Room roo) => new { o.Sn, cus.Price, roo.Balance })
			.ToList();
		tenantDevviceOut.BUZUYIDUN = deviceInfo.Where(s =>
		{
			int result2;
			if (s.Price.HasValue)
			{
				decimal? price = s.Price;
				decimal balance = s.Balance;
				result2 = (((price.GetValueOrDefault() > balance) & price.HasValue) ? 1 : 0);
			}
			else
			{
				result2 = 0;
			}
			return (byte)result2 != 0;
		}).Count();
		return tenantDevviceOut;
	}

	/// <summary>
	/// 获取电量
	/// </summary>
	/// <param name="type">0是当日 1是昨日 2是当月</param>
	/// <returns></returns>
	[HttpGet("/app/tenantincome")]
	public async Task<TenantIncomeOut> Gettenantincome(int type)
	{
		DateTime dateTime = DateTime.Now;
		DateTime nextTime = DateTime.Now.AddDays(-1.0);
		TenantIncomeOut tenantIncomeOut = new TenantIncomeOut();
		switch (type)
		{
		case 0:
			dateTime = DateTime.Now;
			nextTime = dateTime.Date;
			break;
		case 1:
			dateTime = dateTime.Date;
			nextTime = dateTime.AddDays(-1.0);
			break;
		case 2:
			dateTime = DateTime.Now;
			nextTime = DateTime.Parse($"{dateTime.Year}-{dateTime.Month}-1");
			break;
		}
		tenantIncomeOut.WaterConsumption = Math.Round((from u in _reppower.Context.Queryable<WaterConsumptionRecord>()
			where u.CreateTime >= nextTime && u.CreateTime <= dateTime
			select u).Sum((WaterConsumptionRecord u) => u.TotalUsageDifference), 2).ToString() ?? "";
		tenantIncomeOut.PowerConsumption = Math.Round((from u in _reppower.AsQueryable()
			where u.CreateTime >= nextTime && u.CreateTime <= dateTime
			select u).Sum((PowerConsumptionRecord u) => u.CombinedActiveTotalElectricEnergyDifference), 2).ToString() ?? "";
		tenantIncomeOut.Money = Math.Round((from u in _reppay.AsQueryable()
			where u.CreateTime >= nextTime && u.CreateTime <= dateTime && u.IsPay == 1
			select u).Sum((PaymentRecord u) => u.Amount), 2).ToString() ?? "";
		return tenantIncomeOut;
	}

	[HttpGet("/app/tenantwaterusage")]
	public async Task<TenantWaterUsage> GetWaterCountAllDetialUsage(long waterId)
	{
		DateTime dateTime = DateTime.Now;
		TenantWaterUsage tenantWater = new TenantWaterUsage
		{
			AllUse = (Math.Round((await (from u in _rep.Context.Queryable<WaterDevice>()
				where u.Id == waterId
				select u).FirstAsync()).TotalUsage.GetValueOrDefault(), 2).ToString() ?? "")
		};
		DateTime nextTime = DateTime.Parse($"{dateTime.Year}-{dateTime.Month}-1");
		tenantWater.MonthUse = Math.Round((from u in _reppower.Context.Queryable<WaterConsumptionRecord>()
			where u.CreateTime >= nextTime
			select u).Sum((WaterConsumptionRecord u) => u.TotalUsageDifference), 2).ToString() ?? "";
		return tenantWater;
	}

	/// <summary>
	/// 新增租户
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpPost("/app/addtenant")]
	[AllowAnonymous]
	public async Task AddTenant(AppAddTenantInput input)
	{
		string key = "CAPTCHA:" + input.Phone;
		if (!_cache.ContainsKey(key))
		{
			throw Oops.Bah("验证码错误请重新发送");
		}
		string keyValue = _cache.Get<string>(key);
		if (keyValue != input.PhoneNum)
		{
			throw Oops.Bah("验证码错误请重新发送");
		}
		if (await _sysUserRep.AsQueryable().ClearFilter().AnyAsync((SysUser u) => u.Account == input.AdminAccount))
		{
			throw Oops.Bah("该手机号已注册");
		}
		if (!string.IsNullOrWhiteSpace(input.SlaveConnections) && !JSON.IsValid(input.SlaveConnections))
		{
			throw Oops.Oh(ErrorCodeEnum.D1302);
		}
		if (input.TenantType == TenantTypeEnum.Id)
		{
			ConnectionConfig config = _sysTenantRep.AsSugarClient().CurrentConnectionConfig;
			input.DbType = config.DbType;
			input.Connection = config.ConnectionString;
		}
		TenantOutput tenant = input.Adapt<TenantOutput>();
		await _sysTenantRep.InsertAsync(tenant);
		await InitNewTenant(tenant, input.Password);
		await CacheTenant(0L);
	}

	/// <summary>
	/// 新增租户
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpPost("/app/addElement")]
	public async Task AddElement(AppAddTenantInput input)
	{
		string key = "CAPTCHA:" + input.Phone;
		if (!_cache.ContainsKey(key))
		{
			throw Oops.Bah("验证码错误请重新发送");
		}
		string keyValue = _cache.Get<string>(key);
		if (keyValue != input.PhoneNum)
		{
			throw Oops.Bah("验证码错误请重新发送");
		}
		if (await _sysUserRep.AsQueryable().ClearFilter().AnyAsync((SysUser u) => u.Account == input.AdminAccount))
		{
			throw Oops.Bah("该手机号已注册");
		}
		if (!string.IsNullOrWhiteSpace(input.SlaveConnections) && !JSON.IsValid(input.SlaveConnections))
		{
			throw Oops.Oh(ErrorCodeEnum.D1302);
		}
		if (input.TenantType == TenantTypeEnum.Id)
		{
			ConnectionConfig config = _sysTenantRep.AsSugarClient().CurrentConnectionConfig;
			input.DbType = config.DbType;
			input.Connection = config.ConnectionString;
		}
		TenantOutput tenant = input.Adapt<TenantOutput>();
		await _sysTenantRep.InsertAsync(tenant);
		await InitNewTenant(tenant, input.Password);
		await CacheTenant(0L);
	}

	/// <summary>
	/// 新增用户
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpPost("/app/addownerinfo")]
	[AllowAnonymous]
	public async Task AddOwner(AddAppOwnerInput input)
	{
		string key = "CAPTCHA:" + input.PhoneNumber;
		if (!_cache.ContainsKey(key))
		{
			throw Oops.Bah("验证码错误请重新发送");
		}
		string keyValue = _cache.Get<string>(key);
		if (keyValue != input.PhoneNum)
		{
			throw Oops.Bah("验证码错误请重新发送");
		}
		if (await _sysUserRep.Context.Queryable<Owner>().ClearFilter().AnyAsync((Owner u) => u.PhoneNumber == input.PhoneNumber))
		{
			throw Oops.Bah("该手机号已注册");
		}
		Owner tenant = input.Adapt<Owner>();
		tenant.IsEnable = 1;
		tenant.Id = YitIdHelper.NextId();
		tenant.Password = MD5Encryption.Encrypt(input.Password);
		await _sysTenantRep.Context.Insertable(tenant).ExecuteCommandAsync();
	}

	/// <summary>
	/// 新增用户
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpPost("/app/addowner")]
	[AllowAnonymous]
	public async Task BindMeterByOwner(BindRoomMeter input)
	{
		Owner ownerInfo = await (from u in _repEle.Context.Queryable<Owner>().ClearFilter()
			where u.Id == input.Id
			select u).FirstAsync();
		if (ownerInfo == null)
		{
			throw Oops.Bah("当前账户异常");
		}
		long? roomId = null;
		if (input.Type == 0)
		{
			roomId = await (from u in _repEle.AsQueryable().ClearFilter()
				where u.Sn == input.Sn
				select u.RoomId).FirstAsync();
		}
		else
		{
			roomId = await (from u in _repEle.Context.Queryable<WaterDevice>().ClearFilter()
				where u.Sn == input.Sn
				select u.RoomId).FirstAsync();
		}
		if (!roomId.HasValue)
		{
			throw Oops.Bah("当前设备未绑定区域");
		}
		Room roomInfo = await (from u in _repEle.Context.Queryable<Room>().ClearFilter()
			where (long?)u.Id == roomId
			select u).FirstAsync();
		if (roomInfo == null)
		{
			throw Oops.Bah("当前房间信息异常");
		}
		if (roomInfo.OwnerId.HasValue && roomInfo.OwnerId > 0)
		{
			throw Oops.Bah("当前设备已被绑定");
		}
		roomInfo.OwnerId = input.Id;
		ownerInfo.TenantId = roomInfo.TenantId;
		await _repEle.Context.Updateable(ownerInfo).UpdateColumns((Owner u) => new { u.TenantId }).ExecuteCommandAsync();
		await _repEle.Context.Updateable(roomInfo).UpdateColumns((Room u) => new { u.OwnerId }).ExecuteCommandAsync();
		string accessToken = JWTEncryption.Encrypt(expiredTime: await _sysConfigService.GetTokenExpire(), payload: new Dictionary<string, object>
		{
			{ "UserId", ownerInfo.Id },
			{ "TenantId", ownerInfo.TenantId },
			{ "Account", ownerInfo.PhoneNumber },
			{ "RealName", ownerInfo.Name },
			{
				"AccountType",
				AccountTypeEnum.None
			}
		});
		string refreshToken = JWTEncryption.GenerateRefreshToken(accessToken, await _sysConfigService.GetRefreshTokenExpire());
		_httpContextAccessor.HttpContext.SetTokensOfResponseHeaders(accessToken, refreshToken);
		_httpContextAccessor.HttpContext.Response.Headers["access-token"] = accessToken;
		_httpContextAccessor.HttpContext.Response.Headers["x-access-token"] = refreshToken;
		_httpContextAccessor.HttpContext.Response.Headers["Access-Control-Expose-Headers"] = "access-token,x-access-token";
	}

	/// <summary>
	/// 发送验证码
	/// </summary>
	/// <param name="phoneNumber"></param>
	/// <returns></returns>
	[HttpGet("/app/sendSms")]
	[AllowAnonymous]
	public async Task SendSms(string phoneNumber, long? tenantIdInfo)
	{
		long tenantId = 1300000000001L;
		if (tenantIdInfo.HasValue && tenantIdInfo > 0)
		{
			tenantId = tenantIdInfo.Value;
		}
		int type = 0;
		MessageConfig smsConfig = await (from w in _rep.Context.Queryable<MessageConfig>()
			where w.TenantId == (long?)tenantId
			select w).FirstAsync();
		if (smsConfig == null || string.IsNullOrWhiteSpace(smsConfig.SdkAppId) || string.IsNullOrWhiteSpace(smsConfig.SecretId) || string.IsNullOrWhiteSpace(smsConfig.SecretKey) || string.IsNullOrWhiteSpace(smsConfig.SignName))
		{
			throw Oops.Bah("未开通短信服务，请到线下办理");
		}
		var template = await (from w in _rep.Context.Queryable<MessageTemplate>()
			where w.TenantId == (long?)tenantId && w.Type == 0
			select w into s
			select new { s.TemplateId }).FirstAsync();
		if (template == null || string.IsNullOrWhiteSpace(template.TemplateId))
		{
			throw Oops.Bah("未开通短信服务，请到线下办理");
		}
		(SendSmsResponse, List<string>) tuple = await SmsTool.SendCAPTCHA(_cache, phoneNumber, smsConfig.SignName, template.TemplateId, smsConfig.SecretId, smsConfig.SecretKey, smsConfig.SdkAppId);
		SendSmsResponse res = tuple.Item1;
		List<string> @params = tuple.Item2;
		MessageRecord record = new MessageRecord
		{
			PhoneNumber = phoneNumber,
			TenantId = tenantId,
			Type = type,
			Params = @params,
			RequestId = res?.RequestId
		};
		if (res != null && res.SendStatusSet.Length != 0)
		{
			record.Code = ((res != null) ? res.SendStatusSet[0].Code : null);
			record.Message = ((res != null) ? res.SendStatusSet[0].Message : null);
		}
		_rep.Context.Insertable(record).ExecuteCommand();
	}

	/// <summary>
	/// 缓存所有租户
	/// </summary>
	/// <param name="tenantId"></param>
	/// <returns></returns>
	[NonAction]
	public async Task CacheTenant(long tenantId = 0L)
	{
		if (tenantId > 0 && tenantId.ToString() != "1300000000001")
		{
			_sysTenantRep.AsTenant().RemoveConnection(tenantId);
		}
		List<SysTenant> tenantList = await _sysTenantRep.GetListAsync();
		foreach (SysTenant tenant in tenantList)
		{
			tenant.Connection = CryptogramUtil.SM2Encrypt(tenant.Connection);
		}
		_sysCacheService.Set("sys_tenant", tenantList);
	}

	/// <summary>
	/// 新增租户初始化
	/// </summary>
	/// <param name="tenant"></param>
	private async Task InitNewTenant(TenantOutput tenant, string pwd)
	{
		long tenantId = tenant.Id;
		string tenantName = tenant.Name;
		SysOrg newOrg = new SysOrg
		{
			TenantId = tenantId,
			Pid = 0L,
			Name = tenantName,
			Code = tenantName,
			Remark = tenantName
		};
		await _sysOrgRep.InsertAsync(newOrg);
		SysRole newRole = new SysRole
		{
			TenantId = tenantId,
			Name = "租管-" + tenantName,
			Code = "sys_admin",
			DataScope = DataScopeEnum.All,
			Remark = tenantName
		};
		await _sysRoleRep.InsertAsync(newRole);
		SysPos newPos = new SysPos
		{
			TenantId = tenantId,
			Name = "租管-" + tenantName,
			Code = tenantName,
			Remark = tenantName
		};
		await _sysPosRep.InsertAsync(newPos);
		SysUser newUser = new SysUser
		{
			Avatar = "https://aimeter.njsnh.com/Upload/Avatar/40413931822341.png",
			TenantId = tenantId,
			Account = tenant.AdminAccount,
			Password = CryptogramUtil.Encrypt(pwd),
			NickName = "租管",
			Email = tenant.Email,
			Phone = tenant.Phone,
			AccountType = AccountTypeEnum.SysAdmin,
			OrgId = newOrg.Id,
			PosId = newPos.Id,
			Birthday = DateTime.Parse("2000-01-01"),
			RealName = "租管",
			Remark = "租管" + tenantName
		};
		await _sysUserRep.InsertAsync(newUser);
		SysUserRole newUserRole = new SysUserRole
		{
			RoleId = newRole.Id,
			UserId = newUser.Id
		};
		await _userRoleRep.InsertAsync(newUserRole);
		await _sysTenantRep.UpdateAsync((SysTenant u) => new SysTenant
		{
			UserId = newUser.Id,
			OrgId = newOrg.Id
		}, (SysTenant u) => u.Id == tenantId);
		HostString host = _httpContextAccessor.HttpContext.Request.Host;
		new List<long>();
		List<long> menuIdList = ((!host.Host.Contains("dtu.iot-yy.com")) ? new List<long>
		{
			12311806345797L, 12313916281029L, 12319618074437L, 12330570721093L, 12443077761477L, 12443092000197L, 12436345212357L, 11935313219781L, 11935321343941L, 11936236920645L,
			11936241886533L, 11936249154885L, 11936239781317L, 11936346059589L, 11936374051909L, 13448355889349L, 13448400191813L, 13448411917509L, 13450205580997L, 252885263055210L,
			252885263055219L, 252885263055220L, 252885263055211L, 252885263055212L, 252885263055213L, 252885263055214L, 252885263055215L, 252885263055216L, 252885263055217L, 252885263055218L,
			252885263055230L, 252885263055231L, 252885263055232L, 252885263055233L, 252885263055234L, 252885263055235L, 252885263055236L, 252885263055237L, 252885263055240L, 252885263055241L,
			252885263055242L, 252885263055243L, 252885263055244L, 252885263055250L, 252885263055251L, 252885263055252L, 252885263055253L, 252885263055254L, 252885263055260L, 252885263055261L,
			252885263055262L, 252885263055263L, 32760463601221L, 32760470381125L, 32760452963653L, 252885263055270L, 252885263055271L, 252885263055272L, 252885263055273L, 252885263055274L,
			252885263055275L, 252885263055276L, 252885263002100L, 252885263002110L, 13250754741957L, 252885263002111L, 380483319972165L, 380483788312901L, 380484438802757L, 380484517212485L,
			380484647895365L, 380484717478213L, 380509759906117L, 380510367269189L, 380510453645637L, 380510551916869L, 380510616801605L, 12298004106309L, 380529127555397L, 380545449201989L,
			380773809594693L, 380773876453701L, 380774214062405L, 380774288064837L, 380784143425861L, 380784252555589L, 380784318193989L, 380784418595141L, 380784484151621L, 12422559981253L,
			12422570943173L, 12422573051845L, 12422575419205L, 12422568761541L, 11966135992261L, 12288487680453L, 12066766170309L, 11980008422853L, 11980011146053L, 11980015790277L,
			11980017645381L, 12002284353093L, 12010413824069L, 11965678265669L, 11965684472005L, 11965687267525L, 11965689199813L, 11965691057861L, 11965692838341L, 11965696705221L,
			11913647142469L, 12289694546117L, 11913647269061L, 11913647269189L, 11913647269190L, 11913647269317L, 11913647269318L, 11921256499141L, 31966886993989L, 11923512698181L,
			12584850492997L, 12585038425285L, 11923527817669L, 11923612242885L, 11923615208645L, 14321409210437L, 11924202060997L, 11924210494789L, 11932527782853L, 13450812122181L,
			13450852539973L, 13450855721925L, 13450859297989L, 13450963046469L, 13506311643461L, 13506315336645L, 13506318636613L, 13506321222853L, 13506328664005L, 13514497477701L,
			12696046834373L, 12696061149893L, 12696055446085L, 12696063808837L, 13694207416133L, 13694216862917L, 11977313891909L, 11977323133765L, 11980389736645L, 12177544885061L,
			12177554834629L, 12177568131013L, 12311798018373L
		} : new List<long>
		{
			252885263002100L, 252885263002110L, 13250754741957L, 252885263002111L, 380483319972165L, 380483788312901L, 380484438802757L, 380484517212485L, 380484647895365L, 380484717478213L,
			35390081867845L, 380509759906117L, 380510367269189L, 380510453645637L, 380510551916869L, 380510616801605L, 12298004106309L, 380529127555397L, 380545449201989L, 380773809594693L,
			380773876453701L, 380774214062405L, 380774288064837L, 380784143425861L, 380784252555589L, 380784318193989L, 380784418595141L, 380784484151621L, 12422559981253L, 12422570943173L,
			12422573051845L, 12422575419205L, 12422568761541L, 11966135992261L, 12288487680453L, 12066766170309L, 11980008422853L, 11980011146053L, 11980015790277L, 11980017645381L,
			12002284353093L, 12010413824069L, 11965678265669L, 11965684472005L, 11965687267525L, 11965689199813L, 11965691057861L, 11965692838341L, 11965696705221L, 11913647142469L,
			12289694546117L, 11913647269061L, 11913647269189L, 11913647269190L, 11913647269317L, 11913647269318L, 11921256499141L, 31966886993989L, 35262649983813L, 11923512698181L,
			12584850492997L, 12585038425285L, 11923527817669L, 11923612242885L, 11923615208645L, 14321409210437L, 11924202060997L, 11924210494789L, 11932527782853L, 13450812122181L,
			13450852539973L, 13450855721925L, 13450859297989L, 13450963046469L, 13506311643461L, 13506315336645L, 13506318636613L, 13506321222853L, 13506328664005L, 13514497477701L,
			12696046834373L, 12696061149893L, 12696055446085L, 12696063808837L, 13694207416133L, 13694216862917L, 11977313891909L, 11977323133765L, 11980389736645L, 12177544885061L,
			12177554834629L, 12177568131013L, 12311798018373L, 12311806345797L, 12313916281029L, 12319618074437L, 12330570721093L, 12443077761477L, 12443092000197L, 12436345212357L,
			252885263055200L, 11935313219781L, 11935321343941L, 11936236920645L, 11936241886533L, 11936249154885L, 11936239781317L, 11936346059589L, 11936374051909L, 13448355889349L,
			13448400191813L, 13448411917509L, 13450205580997L, 252885263055210L, 252885263055219L, 252885263055220L, 252885263055211L, 252885263055212L, 252885263055213L, 252885263055214L,
			252885263055215L, 252885263055216L, 252885263055217L, 252885263055218L, 34331666044229L, 252885263055230L, 252885263055231L, 252885263055232L, 252885263055233L, 252885263055234L,
			252885263055236L, 252885263055237L, 252885263055235L, 252885263055240L, 252885263055241L, 252885263055242L, 252885263055243L, 252885263055244L, 252885263055250L, 252885263055251L,
			252885263055252L, 252885263055253L, 252885263055254L, 252885263055260L, 252885263055261L, 252885263055262L, 252885263055263L, 32760463601221L, 32760470381125L, 32760452963653L,
			252885263055270L, 252885263055271L, 252885263055272L, 252885263055273L, 252885263055274L, 252885263055275L, 252885263055276L, 252885263055280L, 252885263055282L, 252885263055283L,
			252885263055281L
		});
		await _sysRoleMenuService.GrantRoleMenu(new RoleMenuInput
		{
			Id = newRole.Id,
			MenuIdList = menuIdList
		});
	}
}
